/**
 * Author: grx
 * Description: 展示本日学习记录图表的Fragment
 */
package com.example.parallelandroid;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.parallelandroid.entity.StudyTimeRecord;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.io.File;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DayFragment extends Fragment {

    private BarChart barChart;
    private LineChart lineChart;
    private Button btnSwitch;
    private SQLiteDatabase db;
    private SharedPreferences chart;
    private SharedPreferences.Editor editor;
    private SharedPreferences user;
    private List<StudyTimeRecord> records; // 学习记录
    private List<String> xValues; // 横坐标值
    private List<BarEntry> yValues; // 柱状图纵坐标值
    private List<Entry> yVals; // 折线图纵坐标值

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 获取SharedPreferences
        chart = getContext().getSharedPreferences("studyStatistics", Context.MODE_PRIVATE);
        editor = chart.edit();
        user = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);

        // 在程序内部文件夹中创建数据库文件
        String path = getContext().getFilesDir().getAbsolutePath() + "/database";
        File file = new File(path);
        if (!file.exists()) {
            // 创建文件
            file.mkdirs();
        }
        MyDBHelper myDBHelper = new MyDBHelper(getContext(), "studyRecord.db", null, 1);
        db = myDBHelper.getWritableDatabase(); // 打开数据库

        // 获取布局文件
        View view = inflater.inflate(R.layout.fragment_chart, null);
        // 获取布局文件中的控件对象
        barChart = view.findViewById(R.id.barChart);
        btnSwitch = view.findViewById(R.id.btn_switch);
        lineChart = view.findViewById(R.id.lineChart);
        // 读取本地存储的本日学习记录
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String now = fmt.format(new Date());
        records = findStudyRecords(user.getString("userId", "userId"), now);
        // 初始化柱状图
        initBarChart(records);
        // 设置切换按钮不可见
        btnSwitch.setVisibility(View.INVISIBLE);
        /*// 首次加载本页面时，默认显示柱状图
        // 初始化柱状图
        initBarChart(records);
        editor.putBoolean("isBarChartDay", true);
        editor.commit();
        // 给某"切换"按钮添加事件监听器
        btnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chart.getBoolean("isBarChartDay", false)) {
                    editor.putBoolean("isBarChartDay", false);
                    editor.commit();
                    initLineChart(records);
                } else {
                    editor.putBoolean("isBarChartDay", true);
                    editor.commit();
                    initBarChart(records);
                }
            }
        });*/
        // 返回布局文件对象
        return view;
    }

    // 初始化折线图
    private void initLineChart(List<StudyTimeRecord> records) {
        barChart.setVisibility(View.INVISIBLE); // 设置柱状图不可见
        lineChart.setVisibility(View.VISIBLE); // 设置折线图可见
        btnSwitch.setText("切换为柱状图");
        lineChart.setTouchEnabled(false);
        lineChart.setDragEnabled(true);//设置是否可以拖拽
        lineChart.animateY(1000);
        lineChart.setExtraLeftOffset(10f);
        lineChart.setExtraRightOffset(10f);
        lineChart.getDescription().setEnabled(false);
//        lineChart.setVisibleXRangeMaximum(7); // 设置当前图表中最多在x轴坐标线上显示的刻度线总量为7
        lineChart.setNoDataText("今天还没有学习嗷~");

        // 初始化横纵坐标值
        if (records != null) {
            xValues = initXValues(records);
            lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float v, AxisBase axisBase) {
                    return xValues.get((int)v);
                }
            });
            yVals = initYVals(records);
            LineDataSet lineDataSet = new LineDataSet(yVals, "学习时长/小时");
            // 设置折线图的属性
            //设置线的颜色
//            lineDataSet.setColor(Color.parseColor("#ffffff"));
//            设置线的宽度
            lineDataSet.setLineWidth(2f);
            //设置每个坐标点的圆大小
//            lineDataSet.setCircleRadius(3f);
            //设置圆圈的颜色
//            lineDataSet.setCircleColor(Color.parseColor(lineList.get(j).getColor()));

            LineData lineData = new LineData(lineDataSet);
            lineData.setValueTextSize(15.0f);
            lineChart.setData(lineData);

            //设置一页最大显示个数为7，超出部分就滑动
            float ratio = (float) xValues.size()/(float) 7;
            //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
            lineChart.zoom(ratio,1f,0,0);

            Constant.logger.info("初始化折线图 完成");
        }

        // 绘制轴线
        drawAxis(lineChart.getXAxis()); // X轴
        drawAxis(lineChart.getAxisLeft()); // 左Y轴
        lineChart.getAxisRight().setEnabled(false); // 取消右Y轴
    }

    // 初始化柱状图
    private void initBarChart(List<StudyTimeRecord> records) {
        barChart.setVisibility(View.VISIBLE); // 设置柱状图可见
        lineChart.setVisibility(View.INVISIBLE); // 设置折线图不可见
        btnSwitch.setText("切换为折线图");
        barChart.setTouchEnabled(false);
        barChart.setDragEnabled(true);//设置是否可以拖拽
        barChart.animateY(1000); // 设置动画
        barChart.setExtraRightOffset(10f);
        barChart.getDescription().setEnabled(false);
        //        lineChart.setVisibleXRangeMaximum(7); // 设置当前图表中最多在x轴坐标线上显示的刻度线总量为7
        barChart.setNoDataText("今天还没有学习嗷~");

        // 初始化横纵坐标值
        if (records != null) {
            xValues = initXValues(records);
            barChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float v, AxisBase axisBase) {
                    return xValues.get((int)v);
                }
            });
            yValues = initYValues(records);
            BarDataSet barDataSet = new BarDataSet(yValues, "学习时长/小时");
            barDataSet.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float v, Entry entry, int i, ViewPortHandler viewPortHandler) {
                    // 保留两位小数
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);
                    // 四舍五入
                    nf.setRoundingMode(RoundingMode.UP);
                    return nf.format(v);
                }
            });
            BarData barData = new BarData(barDataSet);
            barData.setValueTextSize(15.0f);
            barChart.setData(barData);

            //设置一页最大显示个数为7，超出部分就滑动
            float ratio = (float) xValues.size()/(float) 7;
            //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
            barChart.zoom(ratio,1f,0,0);
        }

        // 绘制轴线
        drawAxis(barChart.getXAxis()); // X轴
        drawAxis(barChart.getAxisLeft()); // 左Y轴
        barChart.getAxisRight().setEnabled(false); // 取消右Y轴

        Constant.logger.info("初始化柱状图 完成");
    }

    // 绘制轴线
    private void drawAxis(AxisBase mAxis) {
        mAxis.setEnabled(true); // 是否启用轴线
        mAxis.setDrawLabels(true); // 是否开启绘制轴的标签
        mAxis.setDrawAxisLine(true); // 是否绘制轴线
//        mAxis.setDrawGridLines(true); // 绘制网格线
        if (mAxis.getClass() == XAxis.class) {// 如果是x轴
            XAxis xAxis = (XAxis)mAxis;
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setLabelRotationAngle(30); //标签倾斜
            //设置为true当一个页面显示条目过多，X轴值隔一个显示一个
            xAxis.setGranularityEnabled(true);
        }
        if (mAxis.getClass() == YAxis.class) { // 如果是Y轴
            YAxis yAxis = (YAxis)mAxis;
            yAxis.setStartAtZero(true); // 强制Y轴从0开始
            yAxis.setLabelCount(7, true); // 强制设置标签个数
//            yAxis.setAxisMaxValue(6);
        }
    }

    // 初始化纵坐标值: 折线图
    private List<Entry> initYVals(List<StudyTimeRecord> records) {
        List<Entry> yVals = new ArrayList<>();
        if (records != null) {
            for (int i = 0; i < records.size(); i++) {
                yVals.add(new Entry(i, (float) records.get(i).getStudyTime()));
            }
            return yVals;
        } else {
            return null;
        }
    }

    // 初始化纵坐标值: 柱状图
    private List<BarEntry> initYValues(List<StudyTimeRecord> records) {
        List<BarEntry> yValues = new ArrayList<>();
        if (records != null) {
            for (int i = 0; i <records.size(); i++) {
                yValues.add(new BarEntry(i, (float) records.get(i).getStudyTime()));
            }
            return yValues;
        } else {
            return null;
        }
    }

    // 读取本地存储的本日学习记录
    private List<StudyTimeRecord> findStudyRecords(String userId, String date) {
        Constant.logger.info("读取本地存储的学习记录 开始");
        List<StudyTimeRecord> records = null;
        try {
            Cursor result = db.rawQuery("select * from studyRecord where userId = ? and studyDate = ?", new String[]{userId, date});
            if (result.moveToFirst()) {
                records = new ArrayList<>();
                do {
                    int userDateIdIndex = result.getColumnIndex("userDateId");
                    int studyTimeIndex = result.getColumnIndex("studyTime");
                    StudyTimeRecord record = new StudyTimeRecord();
                    record.setUserDateId(result.getString(userDateIdIndex));
                    record.setUserId(userId);
                    record.setStudyTime(result.getFloat(studyTimeIndex));
                    records.add(record);
                } while (result.moveToNext());
            }
            Constant.logger.info("读取本地存储的学习记录: 成功");
        } catch (Exception e) {
            Constant.logger.warn("读取本地存储的学习记录: 失败", e);
        }
        return records;
    }

    // 初始化横坐标值
    private List<String> initXValues(List<StudyTimeRecord> records) {
        List<String> xValues = null;
        if (records != null) {
            int size = records.size();
            xValues = new ArrayList<>();
            for (int i = 1; i <= size; i++) {
                xValues.add("第" + i + "次");
            }
        }
        return xValues;
    }

}
